﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Data.Objects;
using System.Web;
namespace EntityFrameWork
{
    public partial class cbLop : Form
    {
        QLHocSinhEntities qlhs = new QLHocSinhEntities();
        public cbLop()
        {
            InitializeComponent();
            loadSV();
            LoadLop();
        }
        void loadSV()
        {
            gvDanhSach.DataSource = qlhs.HocSinhs.Select(p=>new {
               p.MaHS,p.HoTen,p.GioiTinh,p.NgaySinh,p.DiaChi,p.DTB,p.Lop.TenLop
            });

            // p la bien Aliat dai dien cho nguyen cai ban
            // Frist lay ra record đầu tiên
        }
        void LoadLop()
        {
            cbGioiTinh.Items.Add("Nam");
            cbGioiTinh.Items.Add("Nữ");
            cbLopHoc.DataSource = qlhs.Lops;
            cbLopHoc.DisplayMember = "TenLop";
            cbLopHoc.ValueMember = "MaLop";
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            string ma = cbLopHoc.SelectedValue.ToString();
            Lop l = qlhs.Lops.First(p => p.MaLop == ma);
           
            HocSinh hs = new HocSinh();
                hs.MaHS=txtMaHS.Text;
                hs.HoTen=txtHoten.Text;
                hs.GioiTinh=cbGioiTinh.Text;
                hs.NgaySinh=dateTimePicker1.Value;
                hs.DiaChi=txtDiaChi.Text;
                hs.DTB=double.Parse(txtDTB.Text);
                hs.Lop=l;
                qlhs.AddToHocSinhs(hs);
            qlhs.SaveChanges();
            loadSV();
        }

        private void gvDanhSach_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            txtMaHS.Text = gvDanhSach.Rows[e.RowIndex].Cells[0].Value.ToString();
            txtHoten.Text = gvDanhSach.Rows[e.RowIndex].Cells[1].Value.ToString();
            
        }

        private void btnSua_Click(object sender, EventArgs e)
        {
            HocSinh dshs = qlhs.HocSinhs.First(hs => hs.MaHS == txtMaHS.Text);
            dshs.HoTen = txtHoten.Text;
            qlhs.SaveChanges();
            loadSV();
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            HocSinh dshs = qlhs.HocSinhs.First(hs => hs.MaHS == txtMaHS.Text);
            qlhs.DeleteObject(dshs);
            qlhs.SaveChanges();
            loadSV();
        }
        
    }
}
